from sqlalchemy import Column, create_engine, BigInteger, SmallInteger, Integer, String, DateTime, Boolean, UnicodeText
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from michelangelo import app
import datetime

engine = create_engine(app.config['DATABASE_URI'], convert_unicode=True, pool_recycle=14400)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

Model = declarative_base(name='Model')
Model.query = db_session.query_property()

def init_db():
    Model.metadata.create_all(bind=engine)

class Sms(Model):
    REQUESTING = 0
    SENDING = 1
    ERROR = 2
    SUCCESS = 3
    __tablename__ = 'sms'
    id = Column('id', BigInteger, primary_key=True)
    phone = Column(String(32))
    content = Column(UnicodeText)
    request_time = Column(DateTime)
    schedule_time = Column(DateTime)
    schedule_seconds = Column(Integer)
    status = Column(SmallInteger)
    result = Column(UnicodeText)

    def __init__(self, phone, content, schedule_seconds):
        self.phone = phone
        self.content = content
        self.schedule_seconds = schedule_seconds
        self.status = Sms.REQUESTING
        self.request_time = datetime.datetime.now()
        self.schedule_time = self.request_time + datetime.timedelta(seconds=schedule_seconds)

    def to_dict(self):
      return dict(id=self.id, phone=self.phone, content=self.content, schedule_seconds=self.schedule_seconds, status=self.status)

    def __eq__(self, other):
        return type(self) is type(other) and self.id == other.id

    def __ne__(self, other):
        return not self.__eq__(other)

class Template(Model):
    __tablename__ = 'template'
    id = Column('id', BigInteger, primary_key=True)
    template_id = Column('template_id', BigInteger)
    content = Column(UnicodeText)
    chekc_status = Column(UnicodeText)
    reason = Column(UnicodeText)
